package org.xtense.rcp.editors.util;

import java.util.List;

import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.graphics.Image;
import org.xtense.rcp.util.ITreeEntry;
import org.xtense.rcp.util.ImagesContext;

public class XmlTreeProvider implements ITreeContentProvider,
		ITableLabelProvider {

	@Override
	public Object[] getChildren(Object parentElement) {
		ITreeEntry entry = (ITreeEntry) parentElement;
		return entry.getChildren().toArray();
	}

	@Override
	public Object getParent(Object element) {
		return ((ITreeEntry) element).getParentEntry();
	}

	@Override
	public boolean hasChildren(Object element) {
		ITreeEntry entry = (ITreeEntry) element;
		return !entry.getChildren().isEmpty();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object[] getElements(Object inputElement) {
		if (inputElement instanceof Object[])
			return (Object[]) inputElement;
		else if(inputElement instanceof List)
			return ((List)inputElement).toArray();
		else
			return new Object[0];
	}

	@Override
	public void dispose() {
		// DO NOTHING

	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		// DO NOTHING

	}

	@Override
	public Image getColumnImage(Object element, int columnIndex) {
		ITreeEntry entry = (ITreeEntry) element;
		switch (columnIndex) {
		case 0:
			if (element instanceof XmlEntry) {
				int type = ((XmlEntry) entry).getType();
				if (type == XmlEntry.Attribute)
					return ImagesContext.getImage(ImagesContext.Attribute);
				else if (type == XmlEntry.Element)
					return ImagesContext.getImage(ImagesContext.Element);
			}
			return null;
		case 1:
			if (element instanceof XmlEntry) {
				String text = ((XmlEntry) entry).getValue().trim();
				if(text.length() != 0) {
					return ImagesContext.getImage(ImagesContext.Text);
				} else {
					return null;
				}
			}
		default:
			return null;
		}
	}

	@Override
	public String getColumnText(Object element, int columnIndex) {
		ITreeEntry entry = (ITreeEntry) element;
		switch (columnIndex) {
		case 0:
			return entry.getName();
		case 1:
			if (entry instanceof XmlEntry) {
				return ((XmlEntry) entry).getValue();
			}
			return "";
		default:
			return "";
		}
	}

	@Override
	public void addListener(ILabelProviderListener listener) {
		// DO NOTHING

	}

	@Override
	public boolean isLabelProperty(Object element, String property) {
		// DO NOTHING
		return false;
	}

	@Override
	public void removeListener(ILabelProviderListener listener) {
		// DO NOTHING

	}

}
